package com.twinkle.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.twinkle.gateway.constant.RedisKeyConstants;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 自定义权限验证接口扩展
 */
@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private ObjectMapper objectMapper;
    @SneakyThrows
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        //返回此 loginId 拥有的权限列表
        String userRolesKey = RedisKeyConstants.buildUserRoleKey(Long.valueOf(loginId.toString()));
        String userRoles = redisTemplate.opsForValue().get(userRolesKey);
        if(StringUtils.isBlank(userRoles)) {
            return null;
        }
        List<String> roleKeys = objectMapper.readValue(userRoles, new TypeReference<>() {});
        if (CollUtil.isNotEmpty(roleKeys)) {
            List<String> permissionKeys = roleKeys.stream().map(RedisKeyConstants:: buildRolePermissionsKey).collect(toList());
            // 通过 key 集合批量查询权限，提升查询性能
            List<String> permissionValues = redisTemplate.opsForValue().multiGet(permissionKeys);
            if (CollUtil.isNotEmpty(permissionValues)) {
                List<String> permissions = Lists.newArrayList();
                // 遍历所有角色的权限集合，统一添加到 permissions 集合中
                permissionValues.forEach(jsonValue -> {
                    try {
                        // 将 JSON 字符串转换为 List<String> 权限集合
                        List<String> rolePermissions = objectMapper.readValue(jsonValue, new TypeReference<>() {});
                        permissions.addAll(rolePermissions);
                    } catch (JsonProcessingException e) {
                        log.error("==> JSON 解析错误: ", e);
                    }
                });

                // 返回此用户所拥有的权限
                log.info("用户权限为{}", permissions);
                return permissions;
            }
        }
            return null;
    }


    @SneakyThrows
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        String userRolesKey = RedisKeyConstants.buildUserRoleKey(Long.valueOf(loginId.toString()));
        String userRoles = redisTemplate.opsForValue().get(userRolesKey);
        if(StringUtils.isBlank(userRoles)) {
            return null;
        }
        return objectMapper.readValue(userRoles, new TypeReference<List<String>>() {});
    }

}
